import React from 'react';
import PropTypes from 'prop-types';
import {Button, Form, Row, Col} from 'antd';
const FormItem = Form.Item;
import TextInput from 'Shared/components/TextInput';
import {FORM_OPTIONS} from '../constants';
import WrappedSelect from '../common/WrappedSelect';
import {hasPermissions} from './utils';
import {PERMISSIONS} from './constants';
import {injectIntl} from './intl';
import Export from '../common/Export';
import SearchSelect from 'Shared/components/SearchSelect';
import DealerSelectPanel from './DealerSelectPanel';
import routes from './routes';
import {getDealersQuickly} from './api';
import WrappedInputNumber from '../common/WrappedInputNumber';

class QueryPanel extends React.PureComponent {
    state = {
        data: {
            
        },
        showDealerSelectPanel: false,
    }
    handleFilterChange = (value, name) => {
        this.props.onChange(name, value);
    }
    handleFilterPressEnter = (value, name) => {
        this.props.onChange(name, value);
        this.props.querySearch();
    }
    dealerLabelMap = d => {
        if(d.id === undefined)
            return '';
        if(d)
            return `(${d.code}) ${d.name}`;
        return '';
    }
    onSearchDealer = value =>
        getDealersQuickly({filter: value})
            .then(res => {
                const data = res.data;
                if(data)
                    return data.content;
            })
    onSelectDealer = data => {
        this.props.onChange('dealerId', data.id);
        this.props.onQueryDealerChange({
            id: data.id,
            code: data.code,
            name: data.name,
        });
        this.setState({
            showDealerSelectPanel: false
        });
    }
    onClickSearchDealerBtn = () => {
        this.setState({showDealerSelectPanel: true});
    }
    onCloseDealerSelectPanel = () => {
        this.setState({showDealerSelectPanel: false});
    }
    render() {
        const {formatMessage} = this.props.intl;
        const {data} = this.state;
        const dealerInfo = this.props.dealerInfo.id ? {
            id: this.props.dealerInfo.id,
            code: this.props.dealerInfo.code,
            name: this.props.dealerInfo.name
        } : null;
        return (
            <div>
                <Form className="form-standard">
                    <Row>
                        <Col {...FORM_OPTIONS.col}>
                            <FormItem label={formatMessage({
                                id: 'queryPanel.form.brand',
                                defaultMessage: '品牌'
                            })}{...FORM_OPTIONS.item}>
                                <WrappedSelect
                                    allowClear
                                    name="brandId"
                                    value={this.props.condition.brandId}
                                    options={this.props.brands}
                                    onChange={this.handleFilterChange}/>
                            </FormItem>
                        </Col>
                        <Col {...FORM_OPTIONS.col}>
                            <FormItem label={formatMessage({
                                id: 'queryPanel.form.dealer',
                                defaultMessage: '总代'
                            })} {...FORM_OPTIONS.item}>
                                <SearchSelect
                                    allowClear
                                    value={dealerInfo}
                                    placeholder={this.props.intl.formatMessage({
                                        id: 'queryPanel.form.pleaseQuery',
                                        defaultMessage: '请输入查询'
                                    })}
                                    onSelect={this.onSelectDealer}
                                    onSearch={this.onSearchDealer}
                                    keyIndex="id"
                                    labelMap={this.dealerLabelMap}
                                    onClickSearchBtn={this.onClickSearchDealerBtn} />
                            </FormItem>
                        </Col>
                        <Col {...FORM_OPTIONS.col}>
                            <FormItem label={formatMessage({
                                id: 'queryPanel.form.year',
                                defaultMessage: '年份'
                            })} {...FORM_OPTIONS.item}>
                                <WrappedInputNumber
                                    name="year"
                                    value={this.props.condition.year}
                                    onPressEnter={this.handleFilterPressEnter}
                                    onBlur={this.handleFilterChange} />
                            </FormItem>
                        </Col>
                        <Col {...FORM_OPTIONS.col}>
                            <FormItem label={formatMessage({
                                id: 'queryPanel.form.partCode',
                                defaultMessage: '备件编号（奇瑞）'
                            })} {...FORM_OPTIONS.item}>
                                <TextInput
                                    name="partCode"
                                    value={this.props.condition.partCode}
                                    onPressEnter={this.handleFilterPressEnter}
                                    onBlur={this.handleFilterChange} />
                            </FormItem>
                        </Col>
                        <Col {...FORM_OPTIONS.col}>
                            <FormItem label={formatMessage({
                                id: 'queryPanel.form.partName',
                                defaultMessage: '备件名称（奇瑞）'
                            })} {...FORM_OPTIONS.item}>
                                <TextInput
                                    name="partName"
                                    value={this.props.condition.partName}
                                    onPressEnter={this.handleFilterPressEnter}
                                    onBlur={this.handleFilterChange} />
                            </FormItem>
                        </Col>
                        <Col {...FORM_OPTIONS.col}>
                            <FormItem label={formatMessage({
                                id: 'queryPanel.form.month',
                                defaultMessage: '月份'
                            })} {...FORM_OPTIONS.item}>
                                <WrappedInputNumber
                                    name="month"
                                    value={this.props.condition.month}
                                    onPressEnter={this.handleFilterPressEnter}
                                    onBlur={this.handleFilterChange} />
                            </FormItem>
                        </Col>
                        <Col {...FORM_OPTIONS.col}>
                            <FormItem label={formatMessage({
                                id: 'queryPanel.form.partCodeLocal',
                                defaultMessage: '备件编号（本地）'
                            })} {...FORM_OPTIONS.item}>
                                <TextInput
                                    name="partCodeLocal"
                                    value={this.props.condition.partCodeLocal}
                                    onPressEnter={this.handleFilterPressEnter}
                                    onBlur={this.handleFilterChange} />
                            </FormItem>
                        </Col>
                        <Col {...FORM_OPTIONS.col}>
                            <FormItem label={formatMessage({
                                id: 'queryPanel.form.partNameLocal',
                                defaultMessage: '备件名称（本地）'
                            })} {...FORM_OPTIONS.item}>
                                <TextInput
                                    name="partNameLocal"
                                    value={this.props.condition.partNameLocal}
                                    onPressEnter={this.handleFilterPressEnter}
                                    onBlur={this.handleFilterChange} />
                            </FormItem>
                        </Col>
                    </Row>
                    <Row>
                        <Col span={6}>
                            <Button key="query" type="primary"
                                onClick={this.props.querySearch} loading={this.props.loading}>
                                {formatMessage({
                                    id: 'queryPanel.search',
                                    defaultMessage: '查询'
                                })}</Button>
                            <Button key="clear" onClick={this.props.onClickReset}>{formatMessage({
                                id: 'queryPanel.reset',
                                defaultMessage: '重置'
                            })}</Button>
                        </Col>
                        <Col span={18} className="col-align-right">
                            {hasPermissions(this.props.permission, PERMISSIONS.import) &&
                            <Button key={PERMISSIONS.import} href={`#${routes.import.url()}`}>
                                {this.props.intl.formatMessage({
                                    id: 'queryPanel.operation.import',
                                    defaultMessage: '导入'
                                })}
                            </Button>}
                            {hasPermissions(this.props.permission, PERMISSIONS.export) &&
                                <Export key={PERMISSIONS.export} exportRequest={this.props.onClickExport} />}
                        </Col>
                    </Row>
                    {
                        this.state.showDealerSelectPanel &&
                        <DealerSelectPanel
                            selectKey={data.dealerId}
                            onCancel={this.onCloseDealerSelectPanel}
                            onSelect={this.onSelectDealer} />
                    }
                </Form>
            </div>
        );
    }
}

QueryPanel.propTypes = {
    brands: PropTypes.array.isRequired,
    condition: PropTypes.object.isRequired,
    dealerInfo: PropTypes.object.isRequired,
    initData: PropTypes.object.isRequired,
    loading: PropTypes.bool.isRequired,
    querySearch: PropTypes.func.isRequired,
    onChange: PropTypes.func.isRequired,
    onClickExport: PropTypes.func.isRequired,
    onClickReset: PropTypes.func.isRequired,
    onQueryDealerChange: PropTypes.func.isRequired,
    intl: PropTypes.object,
};

import {connect} from 'react-redux';
import {
    saveQueryCondition,
    querySearch,
    resetQueryPanel,
    exportData,
    saveQueryDealerInfo
} from './actions';
import selectorFactory from 'Shared/utils/immutableToJsSelectorFactory';
import {createSelector} from 'reselect';
const getConditions = selectorFactory(['page', 'appState', 'queryCondition']);
const getInitData = selectorFactory(['page', 'domainData', 'initData']);
const getPermissions = selectorFactory(['page', 'domainData', 'permission', 'data']);
const getDealerInfo = selectorFactory(['page', 'appState', 'dealerInfo']);
const getBrands = createSelector(
    state => state.getIn(['page', 'domainData', 'initData', 'brands']),
    data => {
        const brands = data.toJS();
        return brands
            ? brands.map(item => ({
                value: item.id,
                text: item.code
            }))
            : [];
    }
);
const mapStateToProps = state => ({
    condition: getConditions(state),
    loading: state.getIn((['page', 'domainData', 'list', 'isFetching'])),
    dealerInfo: getDealerInfo(state),
    initData: getInitData(state),
    permission: getPermissions(state),
    brands: getBrands(state),
});

const mapDispatchToProps = dispatch => ({
    onChange: (name, value) => dispatch(saveQueryCondition(name, value)),
    querySearch: () => dispatch(querySearch()),
    onClickReset: () => dispatch(resetQueryPanel()),
    onClickExport: () => dispatch(exportData()),
    onQueryDealerChange: data => dispatch(saveQueryDealerInfo(data)),
});

export default connect(mapStateToProps, mapDispatchToProps)(injectIntl(QueryPanel));
